<template>
	<div class="layout-pd">
    <zh-space style="padding-top: 10px">
      <zh-card title="">
				<zh-form ref="queyFormRef" :model="state.queryParam">
          <zh-form-input
              prop="formCode"
              label="表单编码"
              placeholder="精确查询"
              v-model="state.queryParam.formCode"
            ></zh-form-input>
					<zh-form-input
						prop="formTitle"
						label="表单名称"
						placeholder="支持模糊查询"
						v-model="state.queryParam.formTitle"
					></zh-form-input>
          <template v-if="state.advanced">
            <zh-form-cascader
              prop="formCode"
              label="表单分类"
              placeholder="请选择"
              v-model="state.queryParam.formCode"
              :props="{checkStrictly: true,emitPath:false}"
              :options="state.classSelectTreeData"
            ></zh-form-cascader>
						<zh-form-choose-org prop="orgId" label="所属组织" v-model="state.queryParam.orgId"></zh-form-choose-org>
            <zh-form-cascader
              prop="areaCode"
              label="行政区划"
              placeholder="请选择"
              v-model="state.queryParam.areaCode"
              :props="{checkStrictly: true,emitPath:false}"
              :options="state.areaCodeSelectTreeData"
            ></zh-form-cascader>
            <zh-form-select
              prop="appId"
              :lazy="true"
              label="所属应用"
              v-model="state.queryParam.appId"
              :fieldNames="{ label: 'appName', value: 'appId' }"
              funcCode="application0012"
              searchField="appName"
            ></zh-form-select>
					</template>
					<zh-form-query v-model="state.advanced" :form-ref="queyFormRef" :table-ref="tableListRef">
            <el-checkbox true-label="1" false-label="0" v-model="state.queryParam.historyFlag"><span style="padding-right:10px" >查询其他版本</span></el-checkbox>
          </zh-form-query>
				</zh-form>
			</zh-card>
      <zh-table
				ref="tableListRef"
				title=""
        funcCode="formInfo0001"
				:columns="state.tableColumn"
				:disabled="false"
        :stripe="false"
        :rowConfig="{keyField:'formId'}"
			>
        <template #status_default="{ row }">
					<zh-badge :status="statusMap[row.formStatus].status" :text="statusMap[row.formStatus].text" />
				</template>
        <template #header_button>
          <zh-button button-type="add"  v-func:excelModel0004 @click="addModel()">新建</zh-button>
          <el-tooltip
            effect="dark"
            content="选择表格中的一条信息复制为新版本的初始数据"
            placement="top"
          >
          <zh-button v-func:excelModel0012 button-type="add" @click="copyModel()">复制新建版本</zh-button>
          </el-tooltip>
        </template>
        <template #version_default="{ row }">
          <span style="padding-right:10px">{{row.formVersion}}</span><el-tag  effect="dark" v-if="row.lastFlag==='1'">默认使用</el-tag>
        </template>
        <template #operate_default="{ row }">
          <el-tooltip
            effect="dark"
            content="查看表单基础信息"
            placement="top"
          >
            <zh-button v-func:excelModel0002 button-type="query" link @click="queryModel(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="修改表单基础信息"
            placement="top"
          >
            <zh-button  v-func:excelModel0005 button-type="edit" link @click="editModel(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="设置当前使用"
            placement="top"
          >
            <zh-button v-func:excelModel0011 icon="ele-Setting" link @click="setLastFlag(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="设置表单字段"
            placement="top"
          >
            <zh-button v-func:excelModel0107 type="success" icon="ele-List" link @click="openParams(row)"></zh-button>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="预览"
            placement="top"
          >
            <zh-button icon="ele-View" link @click="openPreview(row)"></zh-button>
          </el-tooltip>

          <el-popconfirm title="是否确认删除该表单?"  @confirm="delModel(row)">
            <template #reference>
                <zh-button v-func:excelModel0006 type="danger" link buttonType="del"></zh-button>
            </template>
          </el-popconfirm>
				</template>
			</zh-table>
    </zh-space>
    <zh-dialog :title="state.modalTitle"  width="90%" v-model="state.visible" >
			<FormInfoForm ref="formInfoPage" v-model="state.visible" :showFlag="state.showFlag" :formInfo="state.selectRow" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">{{state.showFlag?'关闭':'取消'}}</el-button>
          <el-button v-if="!state.showFlag" type="primary" @click="saveModel">
            保存
          </el-button>
        </span>
      </template>
    </zh-dialog>
    <zh-dialog title="表单预览"  width="90%" v-model="state.previewVisible">
      <form-create :rule="state.previewRules" :option="{}"/>
<!--      <form-create :rule="state.formRules2" :option="{}"/>-->
      <form-create :rule="state.formRules" :option="{}"/>
      <template #footer>
        <div></div>
      </template>
    </zh-dialog>
    <zh-dialog title="复制新建版本"  width="35%" v-model="state.copyVisible" @confirm="saveCopyModel">
      <zh-form ref="copyModelFormRef"  :model="state.copyForm" :span="24" :rules="state.copyRules">
			<zh-form-input
				prop="formCode"
        :disabled="true"
				label="表单编号"
				placeholder="请输入表单编号"
				v-model="state.copyForm.formCode"
			></zh-form-input>
      <zh-form-input
				prop="formTitle"
				label="表单名称"
        :disabled="true"
				placeholder="请输入表单名称"
				v-model="state.copyForm.formTitle"
			></zh-form-input>
      <zh-form-input
				prop="formVersion"
				label="版本"
				placeholder="请输入表单版本"
				v-model="state.copyForm.formVersion"
			></zh-form-input>
      </zh-form>
		</zh-dialog>
    <el-drawer
      v-model="state.drawer"
      :title="state.selectRow.formTitle+'('+state.selectRow.formVersion+')~表单设计-简单'"
      direction="rtl"
      destroy-on-close
      :before-close="handleClose"
      size="80%"
    >
    <FormSetting></FormSetting>
      <FormParamsForm ref="formParamsFormRef" :model-info="{formId: state.selectRow.formId}"></FormParamsForm>
      <template #footer>
        <div style="flex: auto;margin-bottom: 10px;margin-right:30px">
          <el-button @click="resetClick">重置</el-button>
          <el-button v-func:excelModel0108 type="primary" @click="confirmClick">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup name="formManager">
import FormInfoForm from './component/FormInfoForm.vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import FormParamsForm from "@/views/system/formCenter/formManager/component/FormParamsForm.vue";
import FormSetting from '@/views/system/formCenter/formDesign/component/FormSetting.vue';

import ZhFormInput from "@/components/zh-form-input/index.vue";
//------------------接收传入参数(组件)-------------------

//------------------定义子组件---------------------------
const queyFormRef=ref()
const tableListRef=ref()
const formInfoPage=ref()
const formParamsFormRef=ref()
const copyModelFormRef=ref()
//------------------内部变量定义-------------------------
const statusMap = {
	0: {
		status: 'error',
		text: '禁用',
	},
	1: {
		status: 'processing',
		text: '启用',
	},
};
const state=reactive({
  formRules2: [
    {
      "formParamsId": "1",
      "formId": "1602864960311922688",
      "type": "zh-form-card",
      "typeName": "zh卡片",
      "field": "aa",
      // "col": {"span": 24},
      "props": {
        "span": 24,
        "title": "title"
      },
      // "children": [
      //   {
      //     "accessToken": null,
      //     "opRouterId": null,
      //     "opFuncId": null,
      //     "opOplogId": null,
      //     "reqIp": null,
      //     "busNo": null,
      //     "formParamsId": "93dd18a12fa146a995c2f6c3d998e614",
      //     "formId": "1602864960311922688",
      //     "type": "zh-form-input",
      //     "typeName": "zh输入框",
      //     "fcDragTag": null,
      //     "field": "8",
      //     "title": "8",
      //     "info": null,
      //     "hidden": null,
      //     "display": null,
      //     "prefix": null,
      //     "suffix": null,
      //     "component": null,
      //     "validate": null,
      //     "optionsTo": null,
      //     "inject": null,
      //     "effect": null,
      //     "link": null,
      //     "col": "8",
      //     "wrap": null,
      //     "control": null,
      //     "emit": null,
      //     "emitPrefix": null,
      //     "props": {
      //       "span": 8
      //     },
      //     "directives": null,
      //     "slot": null,
      //     "parentId": "1",
      //     "fixed": null,
      //     "children": null,
      //     "id": "93dd18a12fa146a995c2f6c3d998e614",
      //     "name": null,
      //     "native": null,
      //     "options": null,
      //     "update": null,
      //     "sync": null,
      //     "class": null,
      //     "style": {
      //       "marginBottom": "15px"
      //     },
      //     "on": null,
      //     "value": 1
      //   }
      // ],
    }
  ],
  formRules: [{type: 'zh-form-card', field: 'x', props: {title: '测试card', label: 'ccc', span: 24,}, children: [
      // {type: 'zh-form-input', field: 'g', value: 'iphone 7', props: {label: '测试', type: 'text',span:8, }},
      // {type: 'zh-form-query', field: 'f', props: {span:'8', formRef: aaaa.value, tableRef: tableListRef.value}},
    ]},

    // {type: 'el-input', field: 'goods', value: 'iphone 7', props: {label: '测试', type: 'text'}},
    // {type: 'el-input', title: '商品名称', field: 'goods_name', value: 'iphone 7', col: {span: 12, labelWidth: 150}, props: {type: 'text',}, validate: [{required: true, message: '请输入goods_name', trigger: 'blur'},],},
    // {type: 'input', title: '商品名称', field: 'goods_name', value: 'iphone 7', col: {span: 12, labelWidth: 150}, props: {type: 'text',}, validate: [{required: true, message: '请输入goods_name', trigger: 'blur'},],},
    // {
    //   type: 'autoComplete',
    //   title: '自动完成',
    //   field: 'auto',
    //   value: 'xaboy',
    //   props: {
    //     fetchSuggestions: function (queryString, cb) {
    //       cb([{value: queryString}, {value: queryString + queryString}]);
    //     }
    //   }
    // },
    // {type: 'InputNumber', field: 'price', title: '价格', value: 1, props: {precision: 2},},
    // {
    //   type: 'Select', field: 'price', title: '价格', value: '105', options: '[\n' +
    //       '        {\'value\': \'104\', \'label\': \'生态蔬菜\', \'disabled\': false},\n' +
    //       '      {\'value\': \'105\', \'label\': \'新鲜水果\', \'disabled\': false},\n' +
    //       '      ]',
    // },
    // {type: 'input', title: '商品名称', field: 'goods_name', value: 'iphone 7', col: {span: 12, labelWidth: 150}, props: {type: 'text',}, validate: [{required: true, message: '请输入goods_name', trigger: 'blur'},],}
    ],
  advanced:false,
  drawer:false,
  copyVisible:false,
  copyForm:{},
  copyRules:{
    excelVersion: [
      {
        required: true,
        message: '请输入表单版本',
        trigger: 'blur',
      },
    ],
  },
  queryParam:{newFlag:'1'},
  flagDictData:[{dictKey:'1',dictValue:'是'},{dictKey:'0',dictValue:'否'}],
  areaCodeSelectTreeData:[],
  classSelectTreeData:[],
  tableColumn:[
    { type: 'seq', width: 60, fixed: 'left', align: 'center', title: '序号', },
    { field: 'formCode', title: '表单编号', fixed: 'left', align: 'center', width: 150 },
		{ field: 'formTitle', title: '表单名称', fixed: 'left', align: 'center', width: 200 },
    { field: 'formVersion', title: '版本', align: 'center',  width: 160,slots: {default: 'version_default'}},
    { field: 'formTypeName', title: '表单类型', align: 'center',  width: 120},
    { field: 'formClassTitle', title: '表单分类',  align: 'center', width: 150 },
    { field: 'formStatus', title: '表单状态',  align: 'center', width: 80,slots: {
				default: 'status_default',
			}, },
    { field: 'remarks', title: '备注',  align: 'center', width: 300 },
    { field: 'orgName', title: '所属组织',  align: 'center', width: 150 },
    { field: 'areaName', title: '所属行政区划',  align: 'center', width: 150 },
    { field: 'appName', title: '所属应用',  align: 'center', width: 150 },
    { field: 'operate', title: '操作', align: 'center',fixed: 'right',  width: 240,slots: {default: 'operate_default'}},
  ],
  selectRow:{},
  visible:false,
  modalTitle:"操作",
  showFlag:false,
  previewVisible: false,
  previewRules: []
})
//------------------定义调用方法-------------------------
function getAreaCodeData() {
	setTimeout(() => {
		$api.common.send.post('dict0026', {}).then((res) => {
			state.areaCodeSelectTreeData = res.result;
		});
	}, 20);
}
function getClassTree() {
	setTimeout(() => {
		$api.common.send.post('formClass0007', {}).then((res) => {
			state.classSelectTreeData = res.result;
		});
	}, 20);
}
const onClose=()=>{
  state.visible = false;
}
const addModel=()=>{
  state.modalTitle = '新增表单';
  let params={lastFlag:'0'}
  state.selectRow=params
  state.showFlag=false;
  state.visible = true;
}
const copyModel=()=>{
  let row=tableListRef.value.getCurrentRecord();
  if(!row||!row.modelCode){
    ElMessage.warning('请先选择一条复制的数据');
    return
  }
  let copyForm={formId:row.formId,formCode:row.formCode,formTitle:row.formTitle}
  state.copyForm=copyForm
  state.copyVisible = true;
}
const saveCopyModel=()=>{
  $api.common.send.post('excelModel0015',state.copyForm).then(()=>{
    ElMessage.success('复制新增成功！');
    state.copyVisible = false;
    state.queryParam.historyFlag='1'
    state.queryParam.formCode=state.copyForm.formCode
    refreshTable();
  });
}
const queryModel=(row)=>{
 state.modalTitle = '查看表单信息';
 state.selectRow=row
 state.showFlag=true
 state.visible = true;
}
const editModel=(row)=>{
  state.modalTitle = '修改表单';
  state.selectRow=row
  state.showFlag=false;
  state.visible = true;
}
const setLastFlag=(row)=>{
  ElMessageBox.confirm(
    '是否确认将此版本('+row.formVersion+')设置为默认导出版本?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }
  )
    .then(() => {
      sendSetNewFlag(row)
    })
    .catch(() => {

    })
}
const sendSetNewFlag=(row)=>{
  let params={formId:row.formId}
  $api.common.send.post('formInfo0013',params).then(()=>{
    ElMessage.success('设置成功！');
    refreshTable();
  });
}
const openParams=(row)=>{
  state.selectRow=row
  state.drawer = true;
}
const delModel=(row)=>{
  let params={id:row.id}
  $api.common.send.post('formInfo0006',params).then(()=>{
    ElMessage.success('删除成功！');
    refreshTable();
  });

}
const handleClose = (done: () => void) => {
  if(!formParamsFormRef.value.isEdit()){
    done()
    return
  }
  ElMessageBox.confirm('是否确认关闭表单设计页面?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const saveModel=()=>{
  formInfoPage.value.save().then(() => {
    state.visible = false;
    state.queryParam.historyFlag='1'
    tableListRef.value.query(state.queryParam)
	});
}
const refreshTable=()=>{
  tableListRef.value.refresh(state.queryParam)
}
const resetClick=()=>{
  formParamsFormRef.value.reset()
}
const confirmClick=()=>{
  formParamsFormRef.value.save()
}
const openPreview = (row) => {
  state.previewVisible = true;
  $api.common.send.post('formInfoParams0008',{formId: row.formId}).then((res)=>{
    if (res.code == 0) {
      let rules = res.result;
      rules.forEach(item => {
        customComponentCast(item);
      })
      console.log('rules', rules);
      state.previewRules = rules;
    }
  });
}
const customComponentCast = (formInfoParams) => {
  // formInfoParams.style = {marginBottom: '15px'};

  // formInfoParams.value = 1;
  if (formInfoParams.col) {
    formInfoParams.col = null;
    // delete formInfoParams.col
  }
  if (formInfoParams.options) {
    // console.log('item.options', item.options);
    formInfoParams.options = JSON.parse(formInfoParams.options);
  }
  if (formInfoParams.props) {
    console.log('formInfoParams.props', formInfoParams.props);
    formInfoParams.props = JSON.parse(formInfoParams.props);
  }
  if (!formInfoParams.children) {
    return;
  }
  for (let childFormInfoParams of formInfoParams.children) {
    customComponentCast(childFormInfoParams);
  }
}
//------------------初始化------------------------------
onMounted(()=>{
  getAreaCodeData();
  getClassTree();
  nextTick(()=>{
    tableListRef.value.query(state.queryParam)
  })
})
//------------设置给父组件调用的数据/方法(组件)-----------

</script>
<style lang="scss" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
